package com.yunysha.DBManager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

import com.yunysha.constants.YunyshaConstants;

public class DBManager {

	Connection conn;

	private DBManager() {
		conn = null;
	}

	public static DBManager init() {
		return new DBManager();
	}

	public Connection doConnect() {

		try {
			String connectionURL = "jdbc:mysql://" + YunyshaConstants.DB_HOST
					+ ":" + YunyshaConstants.DB_PORT + "/"
					+ YunyshaConstants.DB_NAME;

			Class.forName("com.mysql.jdbc.Driver").newInstance();

			conn = DriverManager.getConnection(connectionURL,
					YunyshaConstants.DB_USERNAME, YunyshaConstants.DB_PASSWORD);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return conn;
	}

	public void doDisconnect() {

		try {
			if (conn != null)
				conn.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void setAutoCommit(boolean value) {
		try {
			if (conn != null) {
				conn.setAutoCommit(value);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void doCommit() {
		try {
			if (!conn.getAutoCommit()) {
				conn.commit();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public final PreparedStatement getPreparedStatement(String sqlQuery) {
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sqlQuery,
					Statement.RETURN_GENERATED_KEYS);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return ps;

	}
}
